﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Linq;
using System.Text;
using System.Windows;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    public partial class YCAFWDPLANData : BaseFunction
    {
        SETINTEXDB INTEXDB = new SETINTEXDB();
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        public INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        public string UserID
        {
            get
            {
                return app.User;
            }
        }
        YCAAUTOEKData doc;
        public YCAFWDPLANData()
            : base()
        {
            Helper.GetDate(ref date, ref year, ref month, ref day);
        } 
        public DataSet SetUpUI()
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataRow dwData = null;
            try
            {
                dwData = INTEXDB.ICC_SECTION.NewRow();
                dwData["SDSA"] = "0247";
                SResult = INTEXDBC.QuerySDDAT(dwData, 3);
                SResult.Tables[0].TableName = "ICC_SECTION";
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    row["SDDATEN"] = Helpers.Helper.GetGB2312Value(row["SDDATEN"].ToString());
                }
                SReturn.Merge(SResult);

                dwData = INTEXDB.LIEFDAT.NewLIEFDATRow();
                dwData["LSMANDANT"] = "00";
                dwData["LSGRSCHL"] = "FS ";
                SResult = INTEXDBC.QueryLIEFDAT(dwData, 3);
                foreach (DataRow rx in SResult.Tables[0].Rows)
                {
                    rx["LSNAME1"] = Helper.GetGB2312Value(rx["LSNAME1"].ToString().Trim());
                }
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryFSSTUELI(null, 7);
                dwData = INTEXDB.ICC_SECTION.NewRow();
                dwData["SDSA"] = "9997";
                SResult = INTEXDBC.QuerySDDAT(dwData, 3);
                SResult.Tables[0].TableName = "ICC_MTYPE";
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    row["SDDATEN"] = Helpers.Helper.GetGB2312Value(row["SDDATEN"].ToString());
                }
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public void Refresh()
        {
            EventDispatcher.Instance.RaiseStatus("刷新数据，请稍后", StatusEventType.RunningProgress);
            //刷新数据，若有新的需求则插入
            INTEXDBC.InsertICC_ABAUFM(null, 2);
            INTEXDBC.UpdateICC_ABAUFM(null, 2);//修正克重问题
            INTEXDBC.UpdateICC_ABAUFM(null, 20);//修正克重问题
            INTEXDBC.UpdateICC_ABAUFM(null, 201);//修正克重问题
            INTEXDBC.UpdateICC_ABAUFM(null, 21);//修正主面料，辅料和里料问题
            INTEXDBC.UpdateICC_ABAUFM(null, 221);//标准价格
            INTEXDBC.UpdateICC_ABAUFM(null, 241);//标准价格
            INTEXDBC.UpdateICC_ABAUFM(null, 251);//标准价格
            INTEXDBC.UpdateICC_ABAUFM(null, 261);//标准价格
        }
        public DataSet LoadGXDECKData(DataRow dwInput, string FSSZUSCHN)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataRow dwData = null;
            double wastageek = 0, prodplanrate = 0;
            try
            {
                ///读取汇总信息                
                ///
                dwData = INTEXDB.WDECK.NewRow();
                dwData["WDMANDANT"] = "00";
                dwData["WDTYP"] = "B";
                dwData["WDSA"] = Right(" " + FSSZUSCHN, 1);
                dwData["WDAUFKRS"] = dwInput["KRS"];
                dwData["WDAUFLFD"] = dwInput["LFD"];
                if (dwData["WDAUFLFD"].ToString().Trim() == "000000")
                    dwData["WDAUFLFD"] = "0";
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 921);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "ICC_XDECK";

                    foreach (DataRow row in SResult.Tables[0].Rows)
                    {
                        row["ARTDES"]=Helper.Convert8859P1ToGB2312 (row["ARTDES"].ToString().Trim());
                        row["CDES"] = Helper.Convert8859P1ToGB2312(row["CDES"].ToString().Trim());
                        row["EXART"] = Helper.Convert8859P1ToGB2312(row["EXART"].ToString().Trim());
                        row["EXCOLOR"] = Helper.Convert8859P1ToGB2312(row["EXCOLOR"].ToString().Trim());
                        row["SELLERNAME"] = Helper.Convert8859P1ToGB2312(row["SELLERNAME"].ToString().Trim());  
                        string UM = row["UM"].ToString().Trim();
                        if (UM == "KG")
                        {
                            decimal mtr = System.Convert.ToDecimal(row["MTRREQ"].ToString());
                            decimal fglfd = System.Convert.ToDecimal(row["FGRLFD"].ToString());
                            row["REQ"] = System.Math.Round(mtr * fglfd * System.Convert.ToDecimal(0.001), 1);
                        }
                        row["PLANRATE"] = prodplanrate;
                        row["WASTAGEEK"] = wastageek;
                        row["REQ"] = Convert.ToDouble(row["REQ"].ToString()) * (1 + prodplanrate * 0.01) * (1 + wastageek * 0.01);
                    }
                    SReturn.Merge(SResult);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                EventDispatcher.Instance.RaiseStatus("查询完成", StatusEventType.StopProgress);
            }
            return SReturn;
        }

        public DataSet LoadXDECKData(DataRow dwInput, bool IsPlanned)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            DataRow dwData = null;
            try
            {
                string UM = dwInput["UM"].ToString().Trim();
                double mtr = System.Convert.ToDouble(dwInput["REQ"].ToString());
                double fglfd = System.Convert.ToDouble(dwInput["FGRLFD"].ToString());

                //MBST EKPOS MDECK ABPOS ICC_ABAUFM
                string client = dwInput["MANDANT"].ToString();
                string wakz = "F";
                string art = dwInput["ART"].ToString();
                string var = dwInput["VAR"].ToString();
                string color = dwInput["COLOR"].ToString();
                string abpart = dwInput["ABPART"].ToString();
                string CREF = dwInput["CREF"].ToString();
                string size = "       ";
                string FSSZUSCHN = dwInput["FSSZUSCHN"].ToString();
                //读取库存
                dwData = INTEXDB.WBBST.NewRow();
                dwData["WBBMANDANT"] = client;
                dwData["WBBART"] = art;
                dwData["WBBVAR"] = var;
                dwData["WBBFARBE"] = color;
                SResult = INTEXDBC.QueryICC_WBBST(dwData, 2);
                SResult.Tables[0].TableName = "ICC_STOCK";
                SReturn.Merge(SResult);
                //读取采购              
                art = Left(art + "                                              ", 20);
                var = Left(var + "                ", 3);
                if (UserID.Trim() == "YCAV")
                {
                    SResult = INTEXDBC.QueryICC_EKPOS(client, wakz, art, var, color, size, "", 41);
                }
                else
                {
                    SResult = INTEXDBC.QueryICC_EKPOS(client, wakz, art, var, color, size, "", 4);
                }
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    row["EKPLSART"] = Helper.Convert8859P1ToGB2312(row["EKPLSART"].ToString().Trim());
                    row["EKPLSFB"] = Helper.Convert8859P1ToGB2312(row["EKPLSFB"].ToString().Trim()); 
                }
                SReturn.Merge(SResult);
                //读取锁定数量
                CheckLockedQty(ref SReturn, dwInput);
                //读取明细
                dwData = INTEXDB.ICC_ABAUFM.NewRow();
                dwData["ABAMANDANT"] = client;
                dwData["ABAART"] = Left(art + "                                    ", 20);
                dwData["ABAVAR"] = Left(var + "                                    ", 3);
                dwData["ABAFARBE"] = color;
                dwData["ABAGROE"] = "       ";
                dwData["FSSZUSCHN"] = FSSZUSCHN;
                dwData["ABPART"] = abpart;
                dwData["ABAVKAUFKRS"] = dwInput["ABAVKAUFKRS"].ToString();
                dwData["ABAVKAUFLFD"] = dwInput["ABAVKAUFLFD"].ToString();
                dwData["ABAVKAUFPOS"] = "89";//ABAVKAUFKRS ABPSPGRD
                dwData["ABACOLORREF"] = Left(CREF + "                                                                                                                                                                             ", 100);
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 15);
                if (SResult.Tables.Count > 0)
                {
                    if (UM == "KG")
                    {
                        foreach (DataRow row in SResult.Tables[0].Rows)
                        {
                            mtr = System.Convert.ToDouble(row["ABARESMG"].ToString());
                            double ABAQTYRESERVE = System.Convert.ToDouble(row["ABAQTYRESERVE"].ToString());
                            //fglfd = System.Convert.ToDecimal(row["WAFGRLFD"].ToString());
                            row["ABARESMG"] = System.Math.Round(mtr * fglfd * 0.001, 0);//用于显示而已，系他不保存KG
                            row["ABAQTYRESERVE"] = System.Math.Round(ABAQTYRESERVE * fglfd * 0.001, 2);//用于显示而已，系他不保存KG
                        }
                    }
                    SResult.Tables[0].TableName = "NC_ICC_ABAUFM";
                    SReturn.Merge(SResult);
                }

                #region========该面料相关款==========
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 17);
                if (SResult.Tables.Count > 0)
                {
                    if (UM == "KG")
                    {
                        foreach (DataRow row in SResult.Tables[0].Rows)
                        {
                            mtr = System.Convert.ToDouble(row["ABARESMG"].ToString());
                            double ABAQTYRESERVE = System.Convert.ToDouble(row["ABAQTYRESERVE"].ToString());
                            row["ABARESMG"] = System.Math.Round(mtr * fglfd * 0.001, 0);//用于显示而已，系他不保存KG
                            row["ABAQTYRESERVE"] = System.Math.Round(ABAQTYRESERVE * fglfd * 0.001, 2);//用于显示而已，系他不保存KG
                        }
                    }
                    SResult.Tables[0].TableName = "ICC_ABAUFM";
                    SReturn.Merge(SResult);
                }
                #endregion

                SResult = INTEXDBC.QueryABPOS(dwData, 81);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryABPOS(dwData, 91);
                SResult.Tables[0].TableName = "MX_ABPOS";
                SReturn.Merge(SResult);
                //SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 8);
                //SReturn.Merge(SResult); 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public void BatchReservation(DataRow dwITXSOURCE, SETINTEXDB SetData, bool IsAutoSplit)
        {
            string client = "", art = "", var = "", color = "", size = "", abpart = "", CREF = "";
            string pSType = "B";
            DataSet SResult = new DataSet();
            DataRow dwTemp;
            string UM = "MTR";
            string FSSZUSCHN = " ";
            try
            {
                if (dwITXSOURCE.Table.TableName.Contains("EKPOS"))
                {
                    pSType = "P";
                }
                if (pSType == "P")
                {
                    client = "00";
                    art = dwITXSOURCE["EKPART"].ToString();
                    var = dwITXSOURCE["EKPVAR"].ToString();
                    color = dwITXSOURCE["EKPFARBE"].ToString();
                    size = dwITXSOURCE["EKPGROE"].ToString();
                    UM = dwITXSOURCE["EKPMEEH"].ToString().Trim();
                    FSSZUSCHN = dwITXSOURCE["EKPKF"].ToString().Trim();
                    CREF = dwITXSOURCE["EKPLSGRPBEZ"].ToString();
                    abpart = dwITXSOURCE["ABPART"].ToString();
                    abpart = Helper.ParseSectionStr(abpart);
                    if (FSSZUSCHN.Trim() == "")
                        FSSZUSCHN = " ";
                }

                dwTemp = INTEXDB.ICC_ABAUFM.NewRow();
                dwTemp["ABAMANDANT"] = client;
                dwTemp["ABAART"] = Left(art + "                                    ", 20);
                dwTemp["ABAVAR"] = Left(var + "                                    ", 3);
                dwTemp["ABAFARBE"] = color;
                dwTemp["ABAGROE"] = "       ";
                dwTemp["ABACOLORREF"] = Left(CREF + "                                                                                                                                                                             ", 100);
                dwTemp["FSSZUSCHN"] = FSSZUSCHN;
                //dwTemp["ABAVKAUFKRS"] = "89";//ABAVKAUFKRS ABPSPGRD                
                dwTemp["ABAVKAUFKRS"] = "99";//ABAVKAUFKRS ABPSPGRD                
                dwTemp["ABPART"] = abpart;
                SResult = INTEXDBC.QueryICC_ABAUFM(dwTemp, 151);
                foreach (DataRow row in SResult.Tables[0].Rows)
                {
                    string um = row["WAUEBM"].ToString().Trim();
                    if (um == "KG")
                    {
                        double mtr = System.Convert.ToDouble(row["ABARESMG"].ToString());
                        double fglfd = System.Convert.ToDouble(row["WAFGRLFD"].ToString());
                        row["ABARESMG"] = System.Math.Round(mtr * fglfd * 0.001, 2);
                    }
                }
                SETINTEXDB SAB = new SETINTEXDB();
                SAB.Merge(SResult);
                if (SResult.Tables.Count > 0)
                {
                    double ratio = 1;
                    if (IsAutoSplit)
                    {
                        double pSQTY = System.Convert.ToDouble(dwITXSOURCE["EKPQTYFREE"].ToString());//可用数量
                        ratio = AutoSplit(pSQTY, SResult.Tables[0]);
                    }
                    foreach (DataRow row in SResult.Tables[0].Rows)
                    {
                        Reservation(row, dwITXSOURCE, SAB, ratio);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private double AutoSplit(double qty, DataTable tbDECK)
        {
            double qreq = 0;
            double ratio = 1;
            var qxd = from XD in tbDECK.AsEnumerable()
                      group XD by new
                      {
                          TYP = XD["ABAAUFTYP"].ToString(),
                      }
                          into g
                          select new
                          {
                              KEY = g.Key,
                              ABARESMG = g.Sum(XD => Convert.ToDouble(XD.Field<Decimal>("ABARESMG"))),
                          };
            foreach (var XD in qxd)
            {
                if (XD.KEY.TYP.ToString() == "N")
                {
                    qreq = System.Math.Round(XD.ABARESMG, 2);
                }
            }
            if (qreq > 0)
            {
                ratio = System.Math.Round(qty / qreq, 2);
            }

            return ratio;
        }
        public void Reservation(DataRow dwITXXDECK, DataRow dwSrc, SETINTEXDB SetData, double ratio, double qtyappointed=0)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            string pSKRS = "", pSLFD = "", pSPOS = "", pSAID = "";
            string pSType = "B";
            double pSQTY = 0;
            string UM = dwITXXDECK["WAUEBM"].ToString().Trim();
            double rlfd = System.Convert.ToDouble(dwITXXDECK["WAFGRLFD"].ToString().Trim());
            double EKPME1 = 0;
            try
            {
                if (dwSrc.Table.TableName.Contains("EKPOS"))
                {
                    pSType = "P";
                }
                if (pSType == "P")
                {
                    pSKRS = dwSrc["EKPAUFKRS"].ToString();
                    pSLFD = dwSrc["EKPAUFLFD"].ToString();
                    UM = dwSrc["EKPMEEH"].ToString().Trim();
                    pSPOS = dwSrc["EKPAUFPOS"].ToString();
                    pSAID = dwSrc["EKPAID"].ToString();
                    EventDispatcher.Instance.RaiseStatus("开始:" + pSKRS + pSLFD + pSPOS + pSAID, StatusEventType.RunningProgress);
                    pSQTY = System.Convert.ToDouble(dwSrc["EKPQTYFREE"].ToString());
                    EKPME1 = System.Convert.ToDouble(dwSrc["EKPME1"].ToString());
                }
                if (pSType == "B")
                {
                    pSKRS = dwSrc["LO"].ToString();
                    pSLFD = dwSrc["LB"].ToString();
                    pSPOS = "000";
                    pSAID = dwSrc["BAID"].ToString();
                    pSQTY = System.Convert.ToDouble(dwSrc["QTYFREE"].ToString());
                    EKPME1 = System.Convert.ToDouble(dwSrc["QTY"].ToString());
                }
                if (UM == "KG")
                { }
                else
                    rlfd = 1000;
                pSQTY = Math.Round(pSQTY * 1000 / rlfd, 2);
                EKPME1 = Math.Round(EKPME1 * 1000 / rlfd, 2);

                DataRow row = dwITXXDECK;
                string krs = row["ABAVKAUFKRS"].ToString();
                string lfd = row["ABAVKAUFLFD"].ToString();
                string pos = row["ABAVKAUFPOS"].ToString();
                string mart = row["ABAART"].ToString();
                string mvar = row["ABAVAR"].ToString();
                string mfarbe = row["ABAFARBE"].ToString();
                string msize = row["ABAGROE"].ToString();
                string ABAID = row["ABAID"].ToString();
                if (pSType.Trim() == "")
                    return;
                if (pSQTY <= 0)
                    return;


                var query1 = from rx in SetData.ICC_ABAUFM.AsEnumerable()
                             where rx["ABAID"].ToString() == ABAID
                             select rx;
                if (query1.Count() == 0)
                {
                    query1 = from rx in SetData.Tables["NC_ICC_ABAUFM"].AsEnumerable()
                             where rx["ABAID"].ToString() == ABAID
                             select rx;
                }
                #region======PurchasingOrder=======

                if (pSType == "P")
                {
                    pSKRS = dwSrc["EKPAUFKRS"].ToString();
                    pSLFD = dwSrc["EKPAUFLFD"].ToString();
                    UM = dwSrc["EKPMEEH"].ToString().Trim();
                    pSPOS = dwSrc["EKPAUFPOS"].ToString();
                    pSAID = dwSrc["EKPAID"].ToString();
                    EventDispatcher.Instance.RaiseStatus("开始:" + pSKRS + pSLFD + pSPOS + pSAID, StatusEventType.RunningProgress);
                    pSQTY = Convert.ToDouble(dwSrc["EKPQTYFREE"].ToString());
                    EKPME1 = Convert.ToDouble(dwSrc["EKPME1"].ToString()) / 100;
                    if (UM == "KG")
                    { }
                    else
                        rlfd = 1000;
                    pSQTY = Math.Round(pSQTY * 1000 / rlfd, 2);
                    EKPME1 = Math.Round(EKPME1 * 1000 / rlfd, 2);
                    if (pSQTY <= 0)
                        return;


                    foreach (DataRow rx in query1)
                    {
                        ///2.	若可用数量>需求数量，则用留位数量满足需求，不关闭需求
                        ///3.	若可用数量<需求数量，在不允许执行
                        ///
                        double ABARESMG = System.Convert.ToDouble(rx["ABARESMG"].ToString());
                        string atyp = rx["ABAAUFTYP"].ToString().Trim();
                        string akrs = rx["ABAAUFKRS"].ToString().Trim();
                        string alfd = rx["ABAAUFLFD"].ToString().Trim();
                        string apos = rx["ABAAUFPOS"].ToString().Trim();

                        ABARESMG = System.Math.Round(ABARESMG * ratio / (rlfd * 0.001), 2);
                        if (qtyappointed > 0)
                        {
                            ABARESMG = System.Math.Round((1000 * qtyappointed / rlfd) / 10, 2) * 10;
                        }
                        //rx["ABARESMG"] = rqty;
                        rx["ABAAUFTYP"] = pSType;
                        rx["ABAAUFKRS"] = pSKRS;
                        rx["ABAAUFLFD"] = pSLFD;
                        rx["ABAAUFPOS"] = pSPOS;
                        if (pSQTY >= ABARESMG)
                        {
                            #region====数量足够=====
                            rx["ABAQTYRESERVE"] = ABARESMG;
                            INTEXDBC.UpdateICC_ABAUFM(rx, 10);//这里是满足需求的关系，若是部分满足，则拆分数量
                            if (dwSrc.Table.Columns.Contains("EKPQTYFREE"))
                            {
                                pSQTY -= ABARESMG;
                                if (pSQTY <= 0.01)
                                    pSQTY = 0;
                                dwSrc["EKPQTYFREE"] = Math.Round(pSQTY * rlfd * 0.001, 2);
                                dwSrc["EKPQTYLOCKED"] = System.Math.Round((EKPME1 - pSQTY) * rlfd * 0.001 / 10, 2) * 10;
                            }
                            rx["ABAQTYRESERVE"] = Math.Round(ABARESMG * rlfd * 0.001, 2);
                            //界面显示需要转换回
                            #endregion
                        }
                        else
                        {
                            EventDispatcher.Instance.RaiseStatus("本次采购仅仅满足了部分数量" + pSKRS + pSLFD + pSPOS, StatusEventType.StopProgress);
                            #region====数量不足=========
                            rx["ABAQTYRESERVE"] = pSQTY;
                            if (dwSrc.Table.Columns.Contains("EKPQTYFREE"))
                            {
                                dwSrc["EKPQTYFREE"] = 0;
                                dwSrc["EKPQTYLOCKED"] = System.Math.Round(EKPME1 * rlfd * 0.001 / 10, 2) * 10; ;
                            }
                            // ABAQTYALLOCATE,ABAQTYRESERVE,ABAQTYRECEIVED, 
                            INTEXDBC.UpdateICC_ABAUFM(rx, 10);//这里是满足需求的关系，若是部分满足，则拆分数量                               
                            pSQTY = 0;
                            #endregion
                        }
                    }
                    return;
                }
                #endregion
                #region======Stock=======
                pSKRS = dwSrc["LO"].ToString();
                pSLFD = dwSrc["LB"].ToString();
                pSPOS = "000";
                pSAID = dwSrc["BAID"].ToString();
                pSQTY = System.Convert.ToDouble(dwSrc["QTYFREE"].ToString());
                EKPME1 = System.Convert.ToDouble(dwSrc["QTY"].ToString());
                if (pSQTY <= 0)
                    return;

                foreach (DataRow rx in query1)
                {
                    ///2.	若可用数量>需求数量，则用留位数量满足需求，不关闭需求
                    ///3.	若可用数量<需求数量，在不允许执行
                    ///
                    double ABARESMG = System.Convert.ToDouble(rx["ABARESMG"].ToString());
                    string atyp = rx["ABAAUFTYP"].ToString().Trim();
                    string akrs = rx["ABAAUFKRS"].ToString().Trim();
                    string alfd = rx["ABAAUFLFD"].ToString().Trim();
                    string apos = rx["ABAAUFPOS"].ToString().Trim();
                    string um = rx["WAUEBM"].ToString().Trim();
                    rlfd = System.Convert.ToDouble(rx["WAFGRLFD"].ToString().Trim());
                    ABARESMG = System.Math.Round(ABARESMG * ratio);
                    if (qtyappointed > 0)
                    {
                        if (UM == "KG")
                        {
                            ABARESMG = System.Math.Round((1000 * qtyappointed / rlfd) / 10, 2) * 10;
                        }
                        else
                        {
                            ABARESMG = qtyappointed;
                        }
                    }
                    rx["ABAAUFTYP"] = pSType;
                    rx["ABAAUFKRS"] = pSKRS;
                    rx["ABAAUFLFD"] = pSLFD;
                    rx["ABAAUFPOS"] = pSPOS;
                    if (pSQTY >= ABARESMG)
                    {
                        #region====数量足够=====
                        rx["ABAQTYALLOCATE"] = ABARESMG;
                        pSQTY -= ABARESMG;
                        dwSrc["QTYFREE"] = pSQTY;
                        dwSrc["QTYLOCKED"] = ABARESMG - pSQTY;
                        INTEXDBC.UpdateICC_ABAUFM(rx, 10);//这里是满足需求的关系，若是部分满足，则拆分数量
                        #endregion
                    }
                    else
                    {
                        EventDispatcher.Instance.RaiseStatus("本次采购仅仅满足了部分数量" + pSKRS + pSLFD + pSPOS, StatusEventType.StopProgress);
                        #region====数量不足=====
                        rx["ABAQTYALLOCATE"] = ABARESMG;
                        dwSrc["QTYFREE"] = 0;
                        dwSrc["QTYLOCKED"] = EKPME1;
                        INTEXDBC.UpdateICC_ABAUFM(rx, 10);//这里是满足需求的关系，若是部分满足，则拆分数量                               
                        pSQTY = 0;
                        #endregion
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                EventDispatcher.Instance.RaiseStatus("完成" + pSKRS + pSLFD + pSPOS + pSAID, StatusEventType.StopProgress);
            }

        }
        public void CheckLockedQty(ref DataSet src, DataRow dwInput)
        {
            DataSet SResult = new DataSet();
            DataRow dwData = null;
            dwData = INTEXDB.ICC_ABAUFM.NewRow();
            dwData["ABAMANDANT"] = dwInput["MANDANT"];
            dwData["ABAART"] = Left(dwInput["ART"].ToString() + "                                    ", 20);
            dwData["ABAVAR"] = Left(dwInput["VAR"].ToString() + "                                    ", 3);
            dwData["ABAFARBE"] = dwInput["COLOR"];
            dwData["ABAGROE"] = "       ";
            SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 5);
            foreach (DataRow rz in SResult.Tables[0].Rows)
            {
                string sptype = rz["ABAAUFTYP"].ToString();
                switch (sptype)
                {
                    case "N":
                        break;
                    case "B":
                        var query1 = from DataRow rwz in src.Tables["ICC_STOCK"].AsEnumerable()
                                     where rwz["LO"].ToString().Trim() == rz["ABAAUFKRS"].ToString().Trim()
                                     && rwz["LB"].ToString().Trim() == rz["ABAAUFLFD"].ToString().Trim()
                                     select rwz;
                        foreach (DataRow rwz in query1)
                        {
                            rwz["QTYLOCKED"] = rz["ABAQTYALLOCATE"];
                            rwz["QTYFREE"] = System.Convert.ToDouble(rwz["QTY"].ToString()) - System.Convert.ToDouble(rwz["QTYLOCKED"].ToString());
                        }
                        break;
                    case "P":
                        var query2 = from DataRow rwz in src.Tables["ICC_EKPOS"].AsEnumerable()
                                     where rwz["EKPAUFKRS"].ToString().Trim() == rz["ABAAUFKRS"].ToString().Trim()
                                     && rwz["EKPAUFLFD"].ToString().Trim() == rz["ABAAUFLFD"].ToString().Trim()
                                     && rwz["EKPAUFPOS"].ToString().Trim() == rz["ABAAUFPOS"].ToString().Trim()
                                     select rwz;
                        foreach (DataRow rwz in query2)
                        {
                            decimal fqty = System.Convert.ToDecimal(rz["ABAQTYRESERVE"].ToString());
                            decimal rlfd = System.Convert.ToDecimal(rz["WAFGRLFD"].ToString().Trim());
                            decimal ekqty = System.Convert.ToDecimal(rwz["EKPME1"].ToString());
                            string um = rz["WAUEBM"].ToString().Trim();
                            if (um.Trim() == "KG")
                            {
                                fqty = fqty * rlfd / 1000;
                            }
                            rwz["EKPQTYLOCKED"] = fqty;
                            rwz["EKPQTYFREE"] = ekqty - fqty;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        public DataSet LoadSupplier()
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataRow dwData = INTEXDB.LIEFDAT.NewLIEFDATRow();
            dwData["LSMANDANT"] = "00";
            SResult = INTEXDBC.QueryLIEFDAT(dwData, 3);
            SReturn.Merge(SResult);
            return SReturn;
        }
        public DataSet CreateTempEKPOS(DataTable tbEKPOS)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            List<string> listsup = new List<string>();
            ASCIIEncoding ascII = new System.Text.ASCIIEncoding();
            try
            {
                //读取MS，获取默认供应商，如果没有则是0
                string art = "", var = "", color = "";
                string supplier = "00000000";
                string procesed = "00000000;";
                listsup.Add(supplier);
                /*界面：  	EKPNEUB EKPNEUDB EKPLTERM  EKPLTERM EKPMEEHFKT EKPME1 EKPSMENGE  EKPPRME EKPPREH  	
                 * EKPARTGR EKPART 	EKPVAR 	EKPFARBE           	EKPDESS          	EKPCOL
                 * EKPBESCH    	EKPZUSTAND       	EKPGROE
                 此处        	EKPAUFGRP BE	EKPAUFART  
8	
000001000000	EKPMEEHFKT
                 * //WALIEFNR WABIND
*/
                foreach (DataRow rw in tbEKPOS.Rows)
                {
                    int leadtime = 0;
                    rw["EKPARTGR"] = "3";
                    string csupplier = rw["EKPLIEFNR"].ToString();

                    art = rw["EKPART"].ToString();// ascII.GetString((byte[])rw["EKPART"]);
                    var = rw["EKPVAR"].ToString();// ascII.GetString((byte[])rw["EKPVAR"]);
                    color = rw["EKPFARBE"].ToString();
                    DataRow rms = INTEXDB.WASTAMM.NewWASTAMMRow();
                    rms["WAMANDANT"] = "00";
                    rms["WAART"] = Left(art, 20);
                    rms["WAVAR"] = Left(var, 2);
                    STemp = INTEXDBC.QueryWASTAMM(rms, 2);
                    //WAPROGRP	WAARTGRP
                    //SELECT WAFZUABAK FROM WAFARBEN
                    rms = INTEXDB.WAFARBEN.NewRow();
                    rms["WAFMANDANT"] = "00";
                    rms["WAFART"] = Left(art, 20);
                    rms["WAFVAR"] = Left(var, 2);
                    DataSet SetColor = INTEXDBC.QueryWAFARBEN(rms, 3);
                    string price = "";
                    foreach (DataRow rtemp in STemp.Tables[0].Rows)
                    {
                        rw["EKPWAKZ"] = "F";
                        rw["EKPAUFGRP"] = "B";//'' rtemp["WAPROGRP"].ToString();
                        rw["EKPAUFART"] = "BE";// rtemp["WAARTGRP"].ToString();
                        supplier = rtemp["WALIEFNR"].ToString();
                        if (csupplier == "00000000")
                        {
                            rw["EKPLIEFNR"] = supplier;
                        }
                        price = rtemp["WABIND"].ToString().Trim();
                        if (price == "")
                            price = "0";
                        var query = from DataRow rwc in SetColor.Tables[0].AsEnumerable()
                                    where rwc["WAFART"].ToString().Trim() == art.Trim()
                                    && rwc["WAFZUSATZ"].ToString().Trim() == color.Trim()
                                    select rwc;
                        foreach (DataRow rwc in query)
                        {
                            price = (System.Convert.ToDouble(rwc["WAFZUABAK"].ToString()) * 0.01).ToString();
                        }
                        rw["EKPPRME"] = Right("0000000000" + (System.Convert.ToDouble(price) * 1000).ToString(), 10);
                        //rw["EKPPREH"] = "MTR";
                        rw["EKPMEEHFKT"] = "000001000000";
                        leadtime = 10;

                        if (!procesed.Contains(supplier + ";"))
                        {
                            procesed += supplier + ";";
                            listsup.Add(supplier);
                        }
                        if (!procesed.Contains(csupplier + ";"))
                        {
                            procesed += csupplier + ";";
                            listsup.Add(csupplier);
                        }

                    }
                    rw["EKPLTERM"] = GetDateAddDays(date, leadtime);
                }
                foreach (string sup in listsup)
                {
                    int pos = 1;
                    string lfd = "";
                    string krs = "";
                    var query = from DataRow ekp in tbEKPOS.AsEnumerable()
                                where ekp["EKPLIEFNR"].ToString() == sup
                                select ekp;
                    foreach (DataRow ekp in query)
                    {
                        krs = ekp["EKPAUFKRS"].ToString();
                        if (lfd == "")
                        {
                            lfd =INTEXBL.GetAUFLFD(krs, "EKAUFTR");
                        }
                        ekp["EKPAUFLFD"] = lfd;
                        ekp["EKPAUFPOS"] = Right("000" + pos, 3);
                        pos++;
                    }
                }
                //赋予供应商
                //根据供应商情况，组合采购单，产生EKKOPF
                SResult.Merge(tbEKPOS);
                SResult.Tables[0].TableName = "ICC_EKPOS";
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public string DeleteReservation(SETINTEXDB SetData)
        {
            string orders = "";
            try
            {
                foreach (DataRow row in SetData.ICC_ABAUFM.Rows)
                {
                    if (row["ABAAUFTYP"].ToString().Trim() != "N")
                        continue;
                    row["ABAAUFTYP"] = "X";
                    INTEXDBC.UpdateICC_ABAUFM(row, 5);
                    orders += row["ABAAUFKRS"].ToString() + row["ABAAUFLFD"].ToString();
                    /*INTEXDBC.DeleteICC_ABAUFM("", "", "", "", row, 4);
                    DataRow XD = SetData.FDECK.NewRow();
                    XD["FDMANDANT"] = row["ABAMANDANT"];
                    XD["FDAUFKRS"] = row["ABAVKAUFKRS"];
                    XD["FDAUFLFD"] = row["ABAVKAUFLFD"];
                    XD["FDAUFPOS"] = row["ABAVKAUFPOS"];
                    XD["FDART"] = row["ABAART"];
                    XD["FDVAR"] =Left( row["ABAVAR"].ToString(),2);
                    XD["FDFARBE"] = row["ABAFARBE"];
                    XD["FDGROE"] = row["ABAGROE"];
       
                    INTEXDBC.DeleteFDECK(XD, 2);*/
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return orders;
        }
        public DataSet ITXPurchase(SETINTEXDB SetData, bool IsAutoSplit)
        {
            DataSet SetTmp = new DataSet();
            DataSet SReturn = new DataSet();

            try
            {
                string xml = @"C:\IntexReport\Data\YCAATEK\01Temp\EK" + DateTime.Now.ToFileTime().ToString() + ".XML";
                SetTmp.Clear();
                DataTable tbtemp = SetData.ICC_EKPOS.Copy();
                tbtemp.TableName = "EKPOS_EXT";
                foreach (DataRow rw in tbtemp.Rows)
                {
                    rw["EKPME1"] = System.Math.Round(System.Convert.ToDecimal(rw["EKPME1"].ToString()) * 100, 0);
                    rw["EKPWE1"] = System.Math.Round(System.Convert.ToDouble(rw["EKPME1"].ToString())
                        * System.Convert.ToDouble(rw["EKPPRME"].ToString())
                        * 0.001, 0);
                }
                SetTmp.Merge(tbtemp);
                SetTmp.WriteXml(xml);
                Send2Intex(dicParamater);
                tbtemp.TableName = "ICC_EKPOS";
                SReturn.Merge(tbtemp);
                foreach (DataRow row in tbtemp.Rows)
                {
                    row["EKPQTYFREE"] = System.Convert.ToDouble(row["EKPME1"].ToString()) * 0.01;
                    BatchReservation(row, SetData, IsAutoSplit);
                }
                DataRow dwData = INTEXDB.EKKOPF.NewRow();
                bool IsValid = true;
                string processed = "";
                foreach (DataRow rw in tbtemp.Rows)
                {
                    string mandant = "", krs = "", lfd = "";
                    krs = rw["EKPAUFKRS"].ToString();
                    lfd = rw["EKPAUFLFD"].ToString();
                    if (processed.Contains(krs + lfd + ";"))
                        continue;
                    processed += krs + lfd + ";";
                    doc.ValidateEK(rw, ref IsValid);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                EventDispatcher.Instance.RaiseStatus("全部完成", StatusEventType.StopProgress);
                MessageBox.Show("全部完成创建，请开始打印");
            }
            return SReturn;
        }
        public DataSet LoadABPOSData(DataRow dwInput)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            DataSet STemp = new DataSet();
            DataRow dwData = null;
            try
            {
                dwData = INTEXDB.ICC_ABAUFM.NewRow();
                dwData["ABAMANDANT"] = dwInput["ABPMANDANT"];
                dwData["ABAVKAUFKRS"] = dwInput["ABPAUFKRS"];
                dwData["ABAVKAUFLFD"] = dwInput["ABPAUFLFD"];
                dwData["ABAVKAUFPOS"] = dwInput["ABPAUFPOS"];
                SResult = INTEXDBC.QueryICC_ABAUFM(dwData, 7);
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }
        public void Send2Intex(Dictionary<string, object> dicParamater)
        {
            try
            {
                doc = new YCAAUTOEKData(OracleDB, proxy);
                doc.AutoRun();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public void CheckData(DataSet src, ref bool IsSuccess, ref string msg)
        {
            try
            {
                DataTable tb = src.Tables["ICC_EKPOS"];
                foreach (DataRow rw in tb.Rows)
                {
                    string value = rw["EKPPRME"].ToString().Trim();
                    string order = rw["EKPAUFKRS"].ToString() + rw["EKPAUFLFD"].ToString() + rw["EKPAUFPOS"].ToString();
                    if (value == "" || value == "0")
                    {
                        msg += "请输入" + order + "价格!";
                        IsSuccess = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
    }
}